//
//  UpgradeView.m
//  Weike
//
//  Created by leirz on 14/11/19.
//  Copyright (c) 2014年 winupon. All rights reserved.
//

#import "UpgradeView.h"
#import "AppUtils.h"
#import "CustomIOSAlertView.h"
#import "HttpRequest.h"

@interface UpgradeView()<CustomIOSAlertViewDelegate>
{
    NSString *newVersion;
    NSMutableDictionary *map;
    NSString *updateUrl;

    BOOL isForce;//强制升级
}

@end

@implementation UpgradeView

+ (instancetype)sharedInstance
{
    static UpgradeView *instance;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        instance = [[UpgradeView alloc] init];
    });
    return instance;
}

- (void)checkAppVersion
{
    NSString *url = @"/app_version";
    NSString *currentVersion = [AppUtils currentVersion];
    
    NSDictionary *params = [[NSMutableDictionary alloc] init];
    [[HttpRequest sharedHttpRequest] post:url params:params complete:^(BOOL success, NSDictionary *result) {
        if (success) {
            NSArray *arr= result[@"data"];
            for(NSDictionary *verInfo in arr ){
                NSInteger status = [AppUtils toInteger:verInfo[@"status"]];
                if(status == 1){
                    NSString *newVersion1 = verInfo[@"version"];
                    BOOL isForce1 = NO;//[AppUtils toString:verInfo[@"isForce"]].boolValue;
                    updateUrl = [AppUtils toString:verInfo[@"url"]];
                    NSString *updateInfo = [AppUtils toString:verInfo[@"info"]];
                    // 版本检测
                    CGFloat newVer = [[self getFloatVersion:newVersion1 ] floatValue];
                    CGFloat curVer = [[self getFloatVersion:currentVersion ] floatValue];
                    BOOL hasNewVersion = newVer - curVer >0.0001;
                    // 没有新版本直接登录聊天服务器
                    if (hasNewVersion) {
                        CustomIOSAlertView *alert = [[CustomIOSAlertView alloc] init];
                        UIView *contentView = [self createAlertContentView];
                        UITextView *label = (UITextView *)[contentView viewWithTag:10080];
                        NSString *textValue = isForce1 ? [NSString stringWithFormat:@"发现新版本V%@，当前版本为V%@，请升级到新版本",newVersion1,currentVersion] :[NSString stringWithFormat:@"发现新版本V%@，当前版本为V%@，是否升级到最新版本？",newVersion1,currentVersion];
                        textValue = [NSString stringWithFormat:@"%@\n更新信息:\n%@",textValue,updateInfo];
                        label.text = textValue;
                        alert.containerView =contentView;
                        alert.buttonTitles = isForce1 ? @[@"现在升级"]: @[@"暂不更新",@"立刻升级"];
                        alert.delegate = self;
                        [alert show];
                    }
                    break;
                }
            }
        }
    }];
}


-(UIView*)createAlertContentView
{
    UIView *contentView = [[[NSBundle mainBundle] loadNibNamed:@"UpgradeView" owner:self options:nil] firstObject];

    return contentView;
}

/**
 *  将类似 4.2.2的版本号转换为4.22，即去掉第二个开始后面的小数点
 */
-(NSString*)getFloatVersion:(NSString*)version{
    
    if([AppUtils isEmpty:version] ){
        return @"0";
    }
    if([version hasPrefix:@"V"]){
        version = [version substringFromIndex:1];
    }
    NSMutableString *result = [NSMutableString stringWithString:@""];
    int count = 0;
    for(int i=0;i<version.length;i++){
        NSString *s = [version substringWithRange:NSMakeRange(i,1)];
        if ([s isEqualToString:@"."]){
            if(count>0){
                continue;
            }else{
                count=1;
            }
        }
        [result appendFormat:@"%@",s];
    }
    return [[NSString alloc]initWithString:result];
}


#pragma mark CustomIOSAlertViewDelegate
- (void)customIOS7dialogButtonTouchUpInside:(id)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    CustomIOSAlertView *alert = (CustomIOSAlertView *)alertView;
    switch (buttonIndex) {
        case 0:
            if(isForce){
                NSURL *url = [NSURL URLWithString:updateUrl];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                } else {
                    [Toast makeText:@"无法打开该地址"];
                }

            }else{
                [alert close];
            }
            break;
        case 1:
        {
            NSURL *url = [NSURL URLWithString:updateUrl];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            } else {
                [Toast makeText:@"无法打开该地址"];
            }
        }
            break;
        default:
            break;
    }
}

@end
